<template>
  <div class="feed-container">
    <!-- 顶部状态栏 -->
    <div class="status-bar">
      <span class="status-text">12:00</span>
      <div class="status-icons">
        <span class="icon wifi">📶</span>
        <span class="icon battery">🔋</span>
      </div>
    </div>

    <!-- 头部导航 -->
    <div class="feed-header">
      <div class="header-left">
        <div class="logo">📍</div>
        <div class="nav-tabs">
          <span class="nav-item">关注</span>
          <span class="nav-item active">发现</span>
          <div class="location-selector" @click.stop="toggleLocationDropdown">
            <span class="nav-item location-text">{{ selectedLocation }}</span>
            <span class="location-triangle">▼</span>
            <!-- 地区下拉框 -->
            <div v-if="showLocationDropdown" class="location-dropdown">
              <div 
                v-for="location in locations" 
                :key="location"
                :class="['location-item', { active: selectedLocation === location }]"
                @click="selectLocation(location)"
              >
                {{ location }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="header-actions">
      <button class="search-btn" @click="goToSearch">🔍</button>
        <button class="icon-btn" title="购物车" @click="router.push('/cart')">🛒</button>
        <button class="icon-btn" title="订单" @click="router.push('/orders')">📦</button>
      </div>
    </div>

    <!-- 分类导航栏 -->
    <div class="feed-nav">
      <button v-for="tab in tabs" :key="tab" 
              :class="['nav-tab', { active: activeTab === tab }]"
              @click="switchTab(tab)">
        {{ tab }}
      </button>
      <button class="more-btn" @click="showChannelManage = true">▼</button>
    </div>

    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <div v-else-if="contents.length === 0" class="empty">
      <p>暂无内容</p>
    </div>

    <!-- 推荐商品区域 -->
    <div v-if="recommendedGoods.length > 0" class="recommended-section">
      <h3 class="section-title">为您推荐</h3>
      <div class="goods-grid">
        <div 
          v-for="goods in recommendedGoods" 
          :key="goods.goods_id"
          class="goods-card"
          @click="viewGoodsReview(goods.goods_id)"
        >
          <div class="goods-image" v-if="goods.image_url">
            <img :src="goods.image_url" :alt="goods.name">
          </div>
          <div class="goods-info">
            <h4 class="goods-name">{{ goods.name }}</h4>
            <p class="goods-description" v-if="goods.description">{{ goods.description.substring(0, 30) }}...</p>
            <div class="goods-meta">
              <span class="goods-price" v-if="goods.price">¥{{ goods.price }}</span>
              <span class="goods-category" v-if="goods.category">{{ goods.category }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="feed-grid">
      <div 
        v-for="item in contents" 
        :key="item.id"
        class="content-card"
        @click="viewDetail(item)"
      >
        <div class="card-image" v-if="item.media_urls && item.media_urls.length > 0">
          <img :src="item.media_urls[0]" :alt="item.title">
        </div>
        <div class="card-info">
          <h3 class="card-title">{{ item.title || '无标题' }}</h3>
          <p class="card-content">{{ item.content.substring(0, 50) }}...</p>
          <div class="card-meta">
            <div class="author-info">
              <span class="author-avatar">👤</span>
              <span class="author">@{{ item.author_nickname || '游客' }}</span>
            </div>
            <span class="likes">👍 {{ item.like_count }}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 频道管理弹窗 -->
    <div v-if="showChannelManage" class="channel-modal" @click.self="showChannelManage = false">
      <div class="modal-content">
      <div class="modal-header">
        <h2>我的频道</h2>
        <span class="edit-hint">点击进入我的频道</span>
        <button class="edit-btn" @click="enterEdit">
          <span>{{ isEditing ? '完成' : '进入编辑' }}</span>
          <span class="caret" :class="{ rotate: isEditing }">^</span>
        </button>
      </div>
      <div class="modal-channels">
        <div 
          v-for="channel in myChannels" 
          :key="channel" 
          class="channel-tag my-channel"
          :class="{ editing: isEditing && channel !== '推荐' }"
          @click="isEditing && channel !== '推荐' && removeChannel(channel)"
        >
          {{ isEditing && channel !== '推荐' ? '×' : channel }}
        </div>
      </div>

      <div class="modal-header" style="margin-top: 20px;">
        <h2>推荐频道</h2>
        <span class="edit-hint">点击加入我的频道</span>
      </div>
      <div class="modal-channels">
        <div 
          v-for="channel in recommendedChannels" 
          :key="channel" 
          class="channel-tag recommended-channel"
          @click="addChannel(channel)"
        >
          <span class="plus-icon">+</span>{{ channel }}
        </div>
      </div>
      </div>
    </div>

    <!-- 底部导航栏 -->
           <div class="bottom-nav">
             <div class="nav-item active" @click="router.push('/feed')">
               <span class="nav-icon">🏠</span>
               <span class="nav-label">首页</span>
             </div>
            <div class="nav-item" @click="router.push('/shop')">
               <span class="nav-icon">🛒</span>
               <span class="nav-label">购物</span>
             </div>
             <div class="nav-item highlight" @click="router.push('/publish')">
               <span class="nav-icon-blue">+</span>
               <span class="nav-label">发布</span>
             </div>
             <div class="nav-item">
               <span class="nav-icon">💬</span>
               <span class="nav-label">消息</span>
               <span class="notification-dot">🔴</span>
             </div>
             <div class="nav-item" @click="router.push('/customer-service')">
               <span class="nav-icon">🛟</span>
               <span class="nav-label">客服</span>
             </div>
             <div class="nav-item" @click="router.push('/profile')">
               <span class="nav-icon">👤</span>
               <span class="nav-label">我的</span>
             </div>
           </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from '@/api'

const router = useRouter()

const loading = ref(false)
const recommendedGoods = ref([])
const contents = ref([])
const activeTab = ref('推荐')
const showChannelManage = ref(false)
const isEditing = ref(false)
const myChannels = ref(['推荐', '视频', '直播', '头像', '家装', '汽车', '萌宠', '音乐', '舞蹈', '游戏', '旅行', '摄影'])
const recommendedChannels = ref(['美妆', '健身', '美食', '宠物', '穿搭', '读书', '电影', '科技', '搞笑', '旅游', '摄影'])
const tabs = ref(['推荐', '视频', '直播', '头像', '家装', '汽'])
const currentChannel = ref('推荐') // 当前选中的频道

// 地区选择相关
const selectedLocation = ref('杭州')
const showLocationDropdown = ref(false)
const locations = ref([
  '北京', '上海', '广州', '深圳', '杭州', '南京', '成都', '武汉', 
  '西安', '重庆', '天津', '苏州', '长沙', '郑州', '青岛', '大连',
  '厦门', '福州', '济南', '合肥', '石家庄', '哈尔滨', '长春', '沈阳'
])

// 同步顶部导航栏（显示前6个频道）
const updateTopNav = () => {
  tabs.value = myChannels.value.slice(0, 6).map(ch => {
    // 缩短显示名称
    return ch.length > 2 ? ch.substring(0, 2) : ch
  })
}

// 进入编辑模式
const enterEdit = () => {
  isEditing.value = !isEditing.value
}

// 添加频道到"我的频道"
const addChannel = (channel) => {
  if (!myChannels.value.includes(channel)) {
    myChannels.value.push(channel)
    recommendedChannels.value = recommendedChannels.value.filter(c => c !== channel)
    updateTopNav()
  }
}

// 从"我的频道"删除频道（除了"推荐"）
const removeChannel = (channel) => {
  if (channel === '推荐') return // 不能删除推荐
  if (myChannels.value.includes(channel)) {
    myChannels.value = myChannels.value.filter(c => c !== channel)
    recommendedChannels.value.push(channel)
    updateTopNav()
  }
}

const fetchRecommendations = async () => {
  loading.value = true
  
  try {
    const token = localStorage.getItem('token')
    
    if (!token) {
      // 未登录，返回热门内容
      return
    }

    // 根据当前频道过滤
    let filteredData = []
    
    // 默认使用综合热度排序（点赞量+收藏量）
    // 可以通过sort_by参数指定：popular(综合热度), like(点赞量), collect(收藏量)
    const response = await axios.get('/interests/user/recommendations', {
      params: { 
        limit: 50,  // 请求更多数据用于过滤
        sort_by: 'popular'  // 默认综合热度排序
      },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    if (response.data.success) {
      // 根据当前频道过滤内容
      if (currentChannel.value === '推荐') {
        // 推荐显示所有内容
        filteredData = response.data.data
      } else {
        // 其他频道只显示匹配标签的内容
        filteredData = response.data.data.filter(item => {
          const tags = item.tags || []
          return tags.includes(currentChannel.value)
        })
      }
      
      // 如果过滤后没有内容，显示所有内容
      if (filteredData.length === 0) {
        filteredData = response.data.data.slice(0, 20)
      }
      
      contents.value = filteredData.slice(0, 20)
    }
  } catch (error) {
    console.error('获取推荐失败:', error)
  } finally {
    loading.value = false
  }
}

const viewDetail = (item) => {
  router.push(`/content/${item.id}`)
}

// 跳转到搜索页
const goToSearch = () => {
  router.push('/search')
}

// 切换频道时重新请求
const switchTab = async (tab) => {
  activeTab.value = tab
  currentChannel.value = tab
  await fetchRecommendations()
}

// 切换地区下拉框显示
const toggleLocationDropdown = () => {
  showLocationDropdown.value = !showLocationDropdown.value
}

// 选择地区
const selectLocation = (location) => {
  selectedLocation.value = location
  showLocationDropdown.value = false
  // 可以根据地区重新加载内容
  fetchRecommendations()
}

// 点击外部关闭下拉框
const handleClickOutside = (event) => {
  if (!event.target.closest('.location-selector')) {
    showLocationDropdown.value = false
  }
}

// 获取推荐商品
const fetchRecommendedGoods = async () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      return
    }

    const response = await axios.get('/goods/recommendations/list', {
      params: { limit: 10 },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    recommendedGoods.value = response.data
  } catch (error) {
    console.error('获取推荐商品失败:', error)
  }
}

// 跳转到商品评价页面
const viewGoodsReview = (goodsId) => {
  router.push(`/goods/${goodsId}/review`)
}

// 组件挂载时初始化
onMounted(() => {
  updateTopNav()
  fetchRecommendations()
  fetchRecommendedGoods()
  // 添加全局点击事件监听，用于关闭下拉框
  document.addEventListener('click', handleClickOutside)
})

// 组件卸载时清理
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.feed-container {
  width: 100vw;
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 70px;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 15px;
  background: white;
  font-size: 12px;
}

.status-icons {
  display: flex;
  gap: 5px;
}

/* 头部导航 */
.feed-header {
  background: white;
  padding: 10px 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.logo {
  width: 30px;
  height: 30px;
  background: #ff4757;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.nav-tabs {
  display: flex;
  gap: 15px;
}

.nav-item {
  font-size: 16px;
  color: #333;
  cursor: pointer;
}

.nav-item.active {
  color: #ff4757;
  font-weight: bold;
  border-bottom: 2px solid #ff4757;
  padding-bottom: 5px;
}

/* 地区选择器 */
.location-selector {
  position: relative;
  display: flex;
  align-items: center;
  gap: 3px;
  cursor: pointer;
}

.location-text {
  font-size: 16px;
  color: #333;
}

.location-triangle {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 18px;
  height: 18px;
  background: #ff4757;
  border-radius: 50%;
  color: white;
  font-size: 10px;
  line-height: 1;
  transition: transform 0.3s;
  flex-shrink: 0;
  margin-left: 2px;
}

.location-selector:hover .location-triangle {
  transform: scale(1.1);
}

/* 地区下拉框 */
.location-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  margin-top: 5px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  min-width: 120px;
  max-height: 300px;
  overflow-y: auto;
  z-index: 1000;
  padding: 5px 0;
}

.location-item {
  padding: 10px 15px;
  font-size: 14px;
  color: #333;
  cursor: pointer;
  transition: background-color 0.2s;
}

.location-item:hover {
  background-color: #f5f5f5;
}

.location-item.active {
  color: #ff4757;
  font-weight: bold;
  background-color: #fff0f0;
}

/* 下拉框滚动条样式 */
.location-dropdown::-webkit-scrollbar {
  width: 6px;
}

.location-dropdown::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.location-dropdown::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

.location-dropdown::-webkit-scrollbar-thumb:hover {
  background: #999;
}

.search-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
}
.header-actions { display:flex; align-items:center; gap:8px; }
.icon-btn { background:none; border:none; font-size:18px; cursor:pointer; }

.feed-nav {
  background: white;
  display: flex;
  gap: 15px;
  padding: 10px 15px;
  overflow-x: auto;
  align-items: center;
}

.nav-tab {
  background: none;
  border: none;
  padding: 5px 10px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  white-space: nowrap;
  border-radius: 15px;
  transition: all 0.3s;
}

.nav-tab.active {
  color: #ff4757;
  font-weight: bold;
  background: #fff0f0;
}

.more-btn {
  background: none;
  border: none;
  font-size: 12px;
  color: #999;
  cursor: pointer;
  padding: 5px 10px;
}

.loading {
  text-align: center;
  padding: 50px 20px;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 20px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #007AFF;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty {
  text-align: center;
  padding: 50px 20px;
  color: #999;
}

.feed-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  padding: 10px;
}

.content-card {
  background: white;
  border-radius: 10px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.2s;
}

.content-card:hover {
  transform: translateY(-5px);
}

.card-image {
  width: 100%;
  height: 200px;
  overflow: hidden;
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.card-info {
  padding: 12px;
}

.card-title {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-content {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.card-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 5px;
}

.author-avatar {
  width: 20px;
  height: 20px;
  background: #f0f0f0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
}

.author {
  color: #007AFF;
}

.likes {
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 底部导航栏 */
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 6px 0;
  border-top: 1px solid #f0f0f0;
  z-index: 100;
}

.bottom-nav .nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
  font-size: 11px;
  color: #666;
  cursor: pointer;
  position: relative;
  flex: 1;
}

.bottom-nav .nav-item.active {
  color: #007AFF;
}

.nav-icon {
  font-size: 18px;
}

.nav-icon-blue {
  width: 40px;
  height: 40px;
  background: #007AFF;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
}

.nav-label {
  font-size: 10px;
}

.highlight .nav-label {
  color: #007AFF;
}

.notification-dot {
  position: absolute;
  top: -2px;
  right: 8px;
  width: 6px;
  height: 6px;
  background: #ff4757;
  border-radius: 50%;
}

/* 频道管理弹窗 */
.channel-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: flex-end;
}

.modal-content {
  background: white;
  width: 100%;
  max-height: 80vh;
  padding: 20px;
  border-radius: 20px 20px 0 0;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.modal-header h2 {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.edit-hint {
  font-size: 12px;
  color: #999;
}

.edit-btn {
  background: none;
  border: 1px solid #ddd;
  border-radius: 20px;
  padding: 5px 15px;
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  font-size: 12px;
  color: #666;
}

.caret {
  font-size: 10px;
  transition: transform 0.3s;
}

.caret.rotate {
  transform: rotate(180deg);
}

.modal-channels {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
}

.channel-tag {
  padding: 10px;
  text-align: center;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.my-channel {
  background: #f5f5f5;
  color: #333;
  border: 1px solid #ddd;
}

/* 推荐商品区域 */
.recommended-section {
  background: white;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 10px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
}

.goods-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.goods-card {
  background: #f9f9f9;
  border-radius: 10px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.3s;
}

.goods-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.goods-image {
  width: 100%;
  height: 150px;
  overflow: hidden;
  background: #f0f0f0;
}

.goods-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.goods-info {
  padding: 12px;
}

.goods-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-description {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
  line-height: 1.4;
}

.goods-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.goods-price {
  font-size: 16px;
  font-weight: bold;
  color: #ff4757;
}

.goods-category {
  font-size: 12px;
  color: #999;
  background: #f0f0f0;
  padding: 4px 8px;
  border-radius: 4px;
}

.my-channel.editing {
  background: #ffe6e6;
  color: #ff4757;
  border-color: #ff4757;
  font-weight: bold;
  font-size: 20px;
}

.recommended-channel {
  background: white;
  color: #666;
  border: 1px solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 3px;
}

.plus-icon {
  font-size: 16px;
  color: #999;
}
</style>

